﻿namespace SerialIoDemo.FixedHead.ProtocolModel
{
    /// <summary>
    /// 读写共通的基类
    /// </summary>
    public class BaseProtocol
    {
        public static byte[] PackHead { get; } = new byte[] { 0xaa, 0xbb };

        public byte DevId { set; get; }
        /// <summary>
        /// 获取验证码，（count）不能包含验证码
        /// </summary>
        /// <param name="data">验证数据</param>
        /// <param name="offset">偏移量</param>
        /// <param name="count">不包含验证码的长度</param>
        /// <returns>返回crc校验码</returns>
        protected internal ushort GetCRC(byte[] data, int offset, int count)
        {
            //return BytesHelper.CRC16ByRedundancy(data, offset, offset + count - 1);

            ushort crc = 0;
            for (int i = 0; i < count; i++)
            {
                crc = (ushort)(crc ^ (data[offset + i] << 8));
                for (byte j = 0; j < 8; j++)
                {
                    if ((crc & 0x8000) != 0)
                    {
                        crc = (ushort)((crc << 1) ^ 0x1021);
                    }
                    else crc <<= 1;
                }
            }
            return crc;
        }
    }
}
